package com.crm.miaohe.security;


import com.crm.miaohe.exception.ErrorResponse;
import com.google.gson.Gson;
import org.apache.http.HttpStatus;
import org.springframework.context.MessageSource;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

@Component
public class Oauth2AuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final MessageSource messageSource;

    public Oauth2AuthenticationEntryPoint(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        ErrorResponse err = new ErrorResponse();
        err.setCode(String.valueOf(HttpStatus.SC_UNAUTHORIZED));
        String message = messageSource.getMessage("AUTH000", null, Locale.getDefault());
        err.setMessage(message);
        // 使用fastjson
        String json =  new Gson().toJson(err);
        // 指定响应格式是json
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
